#!/usr/bin/env ruby
########################################################################
#--
#
# FILE:  tikjson.rb -- Example of using the Ruby MikroTik API in Ruby
#                      to execute an API command and retrieve results
#                      in JSON format
#
#++
# Author::    Aaron D. Gifford - http://www.aarongifford.com/
# Copyright:: Copyright (c) 2009-2014, InfoWest, Inc.
# License::   BSD license
#--
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, the above list of authors and contributors, this list of
#    conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. Neither the name of the author(s) or copyright holder(s) nor the
#    names of any contributors may be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S), AUTHOR(S) AND
# CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
# IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), AUTHOR(S), OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# DCONSEQUENTIAL AMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
########################################################################
# encoding: ASCII-8BIT

$LOAD_PATH.unshift(File.dirname(__FILE__)+'/../lib')

require 'rubygems'
require 'mtik'
require 'json'

unless ARGV.length > 3
  STDERR.print("Usage: #{$0} <host> <user> <pass> <command> [<args>...] [<command> [<args> ...]]\n")
  exit(-1)
end

## Detect multiple command sequences and build an array of arrays
## where each outer array element is a command plus arguments:
command = Array.new
i = 3
while i < ARGV.length
  if ARGV[i][0,1] == '/'  ## Command detected...
    command << [ ARGV[i] ]
  else
    command[command.length-1] << ARGV[i]
  end
  i += 1
end

print MTik::command(
  :host=>ARGV[0],
  :user=>ARGV[1],
  :pass=>ARGV[2],
  :command=>command
).to_json + "\n"

